<template>
  <div class="record-container">
    <el-button
      type="primary"
      :icon="ArrowLeft"
      plain
      @click="$router.go(-1)"
      style="margin-bottom: 20px"
    >
      返回主菜单
    </el-button>
    <div class="company-step-container">
      <div class="company-main-row">
        <div class="company-step-side">
          <el-steps
            :active="activeStep"
            class="mb-4"
            :space="200"
            simple
            @change="handleStepChange"
          >
            <el-step title="合同" simple icon="Edit" @click.native="goStep(0)" />
            <el-step
              v-if="isRehandleCertificate"
              title="办证"
              simple
              icon="Picture"
              @click.native="goStep(1)"
            />
          </el-steps>
        </div>
        <div class="company-main-content">
          <div v-show="activeStep === 0">
            <el-card
              v-if="oldContractInfo"
              class="material-block"
              shadow="never"
              style="margin-bottom: 20px"
            >
              <div class="block-title">
                旧合同信息（合同编号：{{ oldContractInfo.contractNumber }}）
              </div>
              <el-descriptions :column="2" border>
                <el-descriptions-item label="合同编号">{{
                  oldContractInfo.contractNumber
                }}</el-descriptions-item>
                <el-descriptions-item label="承租方">{{
                  oldContractInfo.lesseeName
                }}</el-descriptions-item>
                <el-descriptions-item label="租赁期限">{{
                  oldContractInfo.leaseTerm
                }}</el-descriptions-item>
                <el-descriptions-item label="房号">{{
                  oldContractInfo.roomNumber
                }}</el-descriptions-item>
              </el-descriptions>
              <div style="margin-top: 16px">
                <span class="block-title" style="font-size: 16px">合同账单</span>
                <!-- <el-button
                  type="primary"
                  @click="handleAddOldPlan"
                  v-if="!addOldRowVisible"
                  style="margin-bottom: 10px"
                  >新增回款计划</el-button
                > -->
                <el-table :data="oldContractPlans" style="width: 100%; margin-top: 8px">
                  <el-table-column label="缴费周期" width="280">
                    <template #default="scope">
                      <template v-if="editOldRow === scope.$index">
                        <el-date-picker
                          v-model="editOldForm.cycleStart"
                          type="date"
                          placeholder="开始日期"
                          format="YYYY年MM月DD日"
                          value-format="YYYY-MM-DD"
                          style="width: 45%"
                        />
                        <span
                          style="display: inline-block; text-align: center; width: 10%"
                          >至</span
                        >
                        <el-date-picker
                          v-model="editOldForm.cycleEnd"
                          type="date"
                          placeholder="结束日期"
                          format="YYYY年MM月DD日"
                          value-format="YYYY-MM-DD"
                          style="width: 45%"
                        />
                      </template>
                      <template v-else>
                        <span>{{ scope.row.cycle }}</span>
                      </template>
                    </template>
                  </el-table-column>
                  <el-table-column label="单价" width="120">
                    <template #default="scope">
                      <template v-if="editOldRow === scope.$index">
                        <el-input
                          v-model="editOldForm.unitPrice"
                          placeholder="单价"
                        />
                      </template>
                      <template v-else>
                        <span>{{ scope.row.unitPrice }}</span>
                      </template>
                    </template>
                  </el-table-column>
                  <el-table-column label="月度费用" width="120">
                    <template #default="scope">
                      <template v-if="editOldRow === scope.$index">
                        <el-input
                          v-model="editOldForm.monthPrice"
                          placeholder="月度费用"
                        />
                      </template>
                      <template v-else>
                        <span>{{ scope.row.monthPrice }}</span>
                      </template>
                    </template>
                  </el-table-column>
                  <el-table-column label="起算日期" width="180">
                    <template #default="scope">
                      <template v-if="editOldRow === scope.$index">
                        <el-date-picker
                          v-model="editOldForm.startTime"
                          type="date"
                          placeholder="选择日期"
                          format="YYYY年MM月DD日"
                          value-format="YYYY年MM月DD日"
                          style="width: 100%"
                        />
                      </template>
                      <template v-else>
                        <span>{{ scope.row.startTime }}</span>
                      </template>
                    </template>
                  </el-table-column>
                  <el-table-column label="应缴费用金额" width="120">
                    <template #default="scope">
                      <template v-if="editOldRow === scope.$index">
                        <el-input
                          v-model="editOldForm.amount"
                          placeholder="应缴费用金额"
                        />
                      </template>
                      <template v-else>
                        <span>{{ scope.row.amount }}</span>
                      </template>
                    </template>
                  </el-table-column>
                  <el-table-column label="已付金额" width="120">
                    <template #default="scope">
                      <template v-if="editOldRow === scope.$index">
                        <el-input
                          v-model="editOldForm.paidAmount"
                          placeholder="已付金额"
                        />
                      </template>
                      <template v-else>
                        <span>{{ scope.row.paidAmount }}</span>
                      </template>
                    </template>
                  </el-table-column>
                  <el-table-column label="剩余金额" width="120">
                    <template #default="scope">
                      <template v-if="editOldRow === scope.$index">
                        <el-input
                          v-model="editOldForm.remainingAmount"
                          placeholder="剩余金额"
                        />
                      </template>
                      <template v-else>
                        <span>{{ scope.row.remainingAmount }}</span>
                      </template>
                    </template>
                  </el-table-column>
                  <el-table-column label="类型" width="120">
                    <template #default="scope">
                      <template v-if="editOldRow === scope.$index">
                        <el-select v-model="editOldForm.type" placeholder="请选择类型">
                          <el-option label="物业费" value="物业费" />
                          <el-option label="租金" value="租金" />
                          <el-option label="押金" value="押金" />
                          <el-option label="其他" value="其他" />
                        </el-select>
                      </template>
                      <template v-else>
                        <span>{{ scope.row.type }}</span>
                      </template>
                    </template>
                  </el-table-column>
                  <el-table-column label="备注">
                    <template #default="scope">
                      <template v-if="editOldRow === scope.$index">
                        <el-input v-model="editOldForm.remake" placeholder="备注" />
                      </template>
                      <template v-else>
                        <span>{{ scope.row.remake }}</span>
                      </template>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="180" fixed="right">
                    <template #default="scope">
                      <template v-if="editOldRow === scope.$index">
                        <!-- <el-button
                          type="primary"
                          size="small"
                          @click="handleSaveOldPlan(scope.$index)"
                          >保存</el-button
                        >
                        <el-button size="small" @click="handleCancelOldEdit"
                          >取消</el-button
                        > -->
                      </template>
                      <template v-else>
                        <!-- <el-button
                          type="primary"
                          size="small"
                          @click="handleEditOldPlan(scope.$index, scope.row)"
                          >编辑</el-button
                        > -->
                        <!-- <el-button
                          type="danger"
                          size="small"
                          @click="handleDeleteOldPlan(scope.$index, scope.row)"
                          >删除</el-button
                        > -->
                      </template>
                    </template>
                  </el-table-column>
                </el-table>
                <el-empty
                  v-if="!oldContractPlans || oldContractPlans.length === 0"
                  description="暂无回款计划数据"
                />
              </div>
            </el-card>
            <el-tabs v-model="contractType" @tab-click="handleTabChange">
              <el-tab-pane
                v-if="!carrieType || carrieType === '' || carrieType === '孵化器'"
                label="实体"
                name="孵化器"
              ></el-tab-pane>
              <el-tab-pane
                v-if="!carrieType || carrieType === '' || carrieType === '加速器'"
                label="实体"
                name="加速器"
              ></el-tab-pane>
              <el-tab-pane
                v-if="isRehandleCertificate"
                label="虚拟"
                name="虚拟"
              ></el-tab-pane>
            </el-tabs>
            <!-- 旧合同信息展示区域 -->

            <div class="material-upload-row" style="display: block">
              <!-- 回款计划表格 -->

              <el-card
                v-if="contractType === '孵化器'"
                class="material-block"
                shadow="never"
                style="max-width: 100%; min-width: 400px"
              >
                <div class="block-title">合同拟定（孵化器）</div>
                <el-form
                  :model="contractForm"
                  :rules="contractRules"
                  ref="contractFormRef"
                  label-width="110px"
                  :disabled="contractForm.approvalNo"
                  label-position="left"
                >
                  <el-row :gutter="16">
                    <el-col :span="12">
                      <el-form-item label="合同编号" prop="contractNumber">
                        <el-input
                          disabled
                          v-model="contractForm.contractNumber"
                          placeholder="合同编号（自动生成）"
                          style="width: calc(100% - 120px); display: inline-block"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item>
                        <span
                          v-if="!contractForm.contractNumber && !contractForm.id"
                          style="color: red; margin-right: 5px"
                          >*</span
                        >
                        <el-button
                          v-if="!contractForm.contractNumber && !contractForm.id"
                          type="primary"
                          style="margin-left: 8px; vertical-align: top"
                          @click="handleGenerateContractNumber"
                          >生成合同编号</el-button
                        >
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-divider>出租方信息</el-divider>
                  <el-row :gutter="16">
                    <el-col :span="8">
                      <el-form-item label="名称" prop="lessorName">
                        <el-input
                          disabled
                          v-model="contractForm.carrierInfo.lessorName"
                          placeholder="请输入出租方名称"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="联系人" prop="lessorContactPerson">
                        <el-input
                          disabled
                          v-model="contractForm.carrierInfo.lessorContactPerson"
                          placeholder="请输入出租方联系人"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="联系方式" prop="lessorContactInfo">
                        <el-input
                          disabled
                          v-model="contractForm.carrierInfo.lessorContactInfo"
                          placeholder="请输入出租方联系方式"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="16">
                    <el-col :span="8">
                      <el-form-item label="信用代码" prop="lessorCreditCode">
                        <el-input
                          disabled
                          v-model="contractForm.carrierInfo.lessorCreditCode"
                          placeholder="请输入出租方信用代码"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="企业地址" prop="lessorAddress">
                        <el-input
                          disabled
                          v-model="contractForm.carrierInfo.lessorAddress"
                          placeholder="请输入出租方企业地址"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="开户行" prop="lessorBank">
                        <el-input
                          disabled
                          v-model="contractForm.carrierInfo.lessorBank"
                          placeholder="请输入出租方开户行"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="16">
                    <el-col :span="8">
                      <el-form-item label="银行账号" prop="lessorAccount">
                        <el-input
                          disabled
                          v-model="contractForm.carrierInfo.lessorAccount"
                          placeholder="请输入出租方账号"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-divider>承租方信息</el-divider>
                  <el-row :gutter="16">
                    <el-col :span="8">
                      <el-form-item label="名称" prop="lesseeName">
                        <el-input
                          v-model="contractForm.lesseeName"
                          placeholder="请输入承租方名称"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="联系人" prop="lesseeContactPerson">
                        <el-input
                          v-model="contractForm.lesseeContactPerson"
                          placeholder="请输入承租方联系人"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="联系方式" prop="lesseeContactInfo">
                        <el-input
                          v-model="contractForm.lesseeContactInfo"
                          placeholder="请输入承租方联系方式"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="16">
                    <el-col :span="8">
                      <el-form-item label="信用代码" prop="lesseeCreditCode">
                        <el-input
                          v-model="contractForm.lesseeCreditCode"
                          placeholder="请输入承租方信用代码"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="企业地址" prop="lesseeAddress">
                        <el-input
                          v-model="contractForm.lesseeAddress"
                          placeholder="请输入承租方企业地址"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="开户行" prop="lesseeBank">
                        <el-input
                          v-model="contractForm.lesseeBank"
                          placeholder="请输入承租方开户行"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="16">
                    <el-col :span="8">
                      <el-form-item label="银行账号" prop="lesseeAccount">
                        <el-input
                          v-model="contractForm.lesseeAccount"
                          placeholder="请输入承租方账号"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-divider>租赁物信息</el-divider>
                  <el-row :gutter="16">
                    <el-col :span="12">
                      <el-form-item label="项目地址" prop="address">
                        <el-input
                          v-model="contractForm.address"
                          placeholder="请输入项目地址"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="房号" prop="roomNumber">
                        <el-select
                          v-model="contractForm.roomNumber"
                          placeholder="请选择房号"
                          filterable
                          multiple
                          style="width: 100%"
                          @change="handleRoomChange"
                        >
                          <el-option
                            v-for="item in freeRooms"
                            :key="item.id"
                            :label="`${item.zt} - ${
                              item.assetType === 0 ? '房间' : '工位'
                            }：${item.roomNumber}（${getRoomStatusText(item.status)}）`"
                            :value="item.roomNumber"
                            :disabled="isRoomDisabled(item)"
                          >
                            <span
                              :style="{ color: isRoomDisabled(item) ? '#c0c4cc' : '' }"
                            >
                              {{ item.zt }} -
                              {{ item.assetType === 0 ? "房间" : "工位" }}：{{
                                item.roomNumber
                              }}（{{ getRoomStatusText(item.status) }}）
                            </span>
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="16">
                    <el-col :span="8">
                      <el-form-item label="面积（m²）" prop="area">
                        <el-input
                          v-model="contractForm.area"
                          type="number"
                          min="0"
                          placeholder="请输入面积（m²）"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="租赁期限" prop="leaseTerm">
                        <el-date-picker
                          v-model="leaseDateRange"
                          type="daterange"
                          validate-event
                          range-separator="至"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
                          format="YYYY年MM月DD日"
                          value-format="YYYY-MM-DD"
                          style="width: 100%"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="租赁年限" required>
                        <el-input
                          v-model="leaseYears"
                          placeholder="请输入租赁年限（年）"
                          type="number"
                          min="1"
                          style="width: 100%"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-divider>条款信息</el-divider>
                  <el-row :gutter="16">
                    <el-col :span="6">
                      <el-form-item label="免租期（月）" prop="rentFreePeriod">
                        <el-input
                          v-model="contractForm.rentFreePeriod"
                          type="number"
                          min="0"
                          placeholder="可不填，单位：月"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="租金单价(元)" prop="unitRentPrice">
                        <el-input
                          v-model="contractForm.unitRentPrice"
                          type="number"
                          min="0"
                          placeholder="请输入租金单价（元/m²）"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="物业类型" prop="propertyType">
                        <el-select
                          v-model="contractForm.propertyType"
                          placeholder="请选择"
                        >
                          <el-option label="自有物业" value="自有物业" />
                          <el-option label="第三方物业" value="第三方物业" />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6" v-if="contractForm.propertyType === '自有物业'">
                      <el-form-item label="物业费(元/月)" prop="amount">
                        <el-input
                          v-model="contractForm.amount"
                          type="number"
                          min="0"
                          placeholder="请输入物业费"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="保证金（元）" prop="securityDeposit">
                        <el-input
                          v-model="contractForm.securityDeposit"
                          type="number"
                          min="0"
                          placeholder="请输入保证金（元）"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="付款方式">
                        <div
                          style="
                            display: flex;
                            align-items: center;

                            width: 100%;
                          "
                        >
                          <span>付</span>
                          <el-input
                            v-model="payNum"
                            type="number"
                            min="1"
                            placeholder="付"
                            style="width: 120px"
                          />
                          <span>押</span>
                          <el-input
                            v-model="depositNum"
                            type="number"
                            min="0"
                            placeholder="押"
                            style="width: 120px"
                          />
                        </div>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="16">
                    <el-col :span="24">
                      <el-form-item label="备注" prop="remark">
                        <el-input
                          v-model="contractForm.remark"
                          type="textarea"
                          placeholder="请输入备注"
                        /> </el-form-item
                    ></el-col>
                  </el-row>
                  <el-row :gutter="16">
                    <el-col :span="4">
                      <span style="color: red; margin-right: 5px">*</span>
                      <el-button type="success" @click="handleDraftContract"
                        >信息保存</el-button
                      >
                    </el-col>
                  </el-row>
                </el-form>
                <el-card
                  v-if="contractForm.contractNumber && contractType != '虚拟'"
                  shadow="never"
                  style="margin: 24px 0; padding: 0"
                  body-style="padding: 0"
                >
                  <div
                    style="
                      display: flex;
                      justify-content: space-between;
                      align-items: center;
                      margin-bottom: 12px;
                    "
                  >
                    <span class="block-title">回款计划</span>
                    <el-button
                      type="primary"
                      @click="handleAddPlan"
                      v-if="!addRowVisible"
                      :disabled="contractForm.approvalNo"
                      >新增回款计划</el-button
                    >
                  </div>

                  <el-table :data="tableData" style="width: 100%">
                    <el-table-column label="缴费周期" width="280">
                      <template #default="scope">
                        <template v-if="editRow === scope.$index">
                          <el-date-picker
                            v-model="editForm.cycleStart"
                            type="date"
                            placeholder="开始日期"
                            format="YYYY年MM月DD日"
                            value-format="YYYY-MM-DD"
                            style="width: 45%"
                          />
                          <span
                            style="display: inline-block; text-align: center; width: 10%"
                            >至</span
                          >
                          <el-date-picker
                            v-model="editForm.cycleEnd"
                            type="date"
                            placeholder="结束日期"
                            format="YYYY年MM月DD日"
                            value-format="YYYY-MM-DD"
                            style="width: 45%"
                          />
                        </template>
                        <template v-else>
                          <span>{{ scope.row.cycle }}</span>
                        </template>
                      </template>
                    </el-table-column>
                    <el-table-column label="单价" width="120">
                      <template #default="scope">
                        <template v-if="editRow === scope.$index">
                          <el-input v-model="editForm.unitPrice" placeholder="单价" />
                        </template>
                        <template v-else>
                          <span>{{ scope.row.unitPrice }}</span>
                        </template>
                      </template>
                    </el-table-column>
                    <el-table-column label="月度费用" width="120">
                      <template #default="scope">
                        <template v-if="editRow === scope.$index">
                          <el-input
                            v-model="editForm.monthPrice"
                            placeholder="月度费用"
                          />
                        </template>
                        <template v-else>
                          <span>{{ scope.row.monthPrice }}</span>
                        </template>
                      </template>
                    </el-table-column>
                    <el-table-column label="起算日期" width="180">
                      <template #default="scope">
                        <template v-if="editRow === scope.$index">
                          <el-date-picker
                            v-model="editForm.startTime"
                            type="date"
                            placeholder="选择日期"
                            format="YYYY年MM月DD日"
                            value-format="YYYY年MM月DD日"
                            style="width: 100%"
                          />
                        </template>
                        <template v-else>
                          <span>{{ scope.row.startTime }}</span>
                        </template>
                      </template>
                    </el-table-column>
                    <el-table-column label="应缴费用金额" width="120">
                      <template #default="scope">
                        <template v-if="editRow === scope.$index">
                          <el-input
                            v-model="editForm.amount"
                            placeholder="应缴费用金额"
                          />
                        </template>
                        <template v-else>
                          <span>{{ scope.row.amount }}</span>
                        </template>
                      </template>
                    </el-table-column>
                    <el-table-column label="类型" width="120">
                      <template #default="scope">
                        <template v-if="editRow === scope.$index">
                          <el-select v-model="editForm.type" placeholder="请选择类型">
                            <el-option label="物业费" value="物业费" />
                            <el-option label="租金" value="租金" />
                            <el-option label="押金" value="押金" />
                            <el-option label="其他" value="其他" />
                          </el-select>
                        </template>
                        <template v-else>
                          <span>{{ scope.row.type }}</span>
                        </template>
                      </template>
                    </el-table-column>
                    <el-table-column label="备注" width="150">
                      <template #default="scope">
                        <template v-if="editRow === scope.$index">
                          <el-input v-model="editForm.remake" placeholder="备注" />
                        </template>
                        <template v-else>
                          <span>{{ scope.row.remake }}</span>
                        </template>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="180">
                      <template #default="scope">
                        <template v-if="editRow === scope.$index">
                          <el-button
                            type="success"
                            size="small"
                            :disabled="contractForm.approvalNo"
                            @click="handleSavePlan(scope.row)"
                            >保存</el-button
                          >
                          <el-button
                            type="info"
                            size="small"
                            :disabled="contractForm.approvalNo"
                            @click="handleCancelEdit(scope.$index)"
                            >取消</el-button
                          >
                        </template>
                        <template v-else>
                          <el-button
                            type="primary"
                            size="small"
                            :disabled="contractForm.approvalNo"
                            @click="handleEdit(scope.$index, scope.row)"
                            >编辑</el-button
                          >
                          <el-button
                            type="danger"
                            size="small"
                            :disabled="contractForm.approvalNo"
                            @click="handleDelete(scope.$index, scope.row)"
                            >删除</el-button
                          >
                        </template>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-card>
                <el-form :inline="true" label-width="110px" label-position="top">
                  <span
                    style="color: red; margin-right: 5px"
                    v-if="contractForm.contractNumber"
                    >*</span
                  ><el-button
                    type="primary"
                    @click="handleCreatedDraftContract"
                    v-if="contractForm.contractNumber"
                    >生成合同</el-button
                  >
                  <el-form-item>
                    <span style="text-align: center; margin-top: 5px; margin-left: 5px"
                      >会签人:</span
                    >
                  </el-form-item>
                  <el-form-item>
                    <el-select
                      v-model="contractForm.counterSignUsers"
                      multiple
                      filterable
                      remote
                      reserve-keyword
                      placeholder="请输入用户名搜索"
                      :remote-method="handleCounterSignUserSearch"
                      :loading="counterSignUsersLoading"
                      style="width: 220px"
                      :remote-show-suffix="true"
                      @visible-change="handleCounterSignUserVisibleChange"
                    >
                      <div
                        style="max-height: 200px; overflow-y: auto"
                        @scroll.passive="handleCounterSignUserScroll"
                      >
                        <el-option
                          v-for="item in counterSignUsers"
                          :key="item.userId"
                          :label="item.nickName"
                          :value="item.userId"
                        />
                      </div>
                    </el-select>
                  </el-form-item>
                  <el-form-item>
                    <span style="color: red; margin-right: 5px">*</span
                    ><el-button
                      type="success"
                      :disabled="contractForm.approvalNo"
                      @click="createFeiShuSealTaskBtn"
                      v-if="contractForm.contractNumber"
                      >发起飞书用印审批</el-button
                    >
                    <div
                      v-if="contractForm.approvalNo"
                      style="color: red; position: absolute; top: 35px; left: 0"
                    >
                      已创建飞书流程，当前状态：{{
                        contractForm.approvalStatus == "ERROR"
                          ? "创建失败"
                          : contractForm.approvalStatus == "PENDING"
                          ? "审批中"
                          : "通过"
                      }}
                    </div>
                  </el-form-item>
                </el-form>
              </el-card>
              <!-- 加速器表单 -->
              <el-card
                v-if="contractType === '加速器'"
                class="material-block"
                shadow="never"
                style="max-width: 100%; min-width: 400px"
              >
                <div class="block-title">合同拟定（加速器）</div>
                <el-form
                  :model="contractForm"
                  :rules="contractRules"
                  ref="contractFormRef"
                  label-width="110px"
                  :disabled="contractForm.approvalNo"
                  label-position="left"
                >
                  <el-row :gutter="16">
                    <el-col :span="12">
                      <el-form-item label="合同编号" prop="contractNumber">
                        <el-input
                          v-model="contractForm.contractNumber"
                          placeholder="合同编号（自动生成）"
                          disabled
                          style="width: calc(100% - 120px); display: inline-block"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <span
                        v-if="!contractForm.contractNumber && !contractForm.id"
                        style="color: red; margin-right: 5px"
                        >*</span
                      >
                      <el-button
                        v-if="contractForm.contractNumber === '' && !contractForm.id"
                        type="primary"
                        style="margin-left: 8px; vertical-align: top"
                        @click="handleGenerateContractNumber"
                        >生成合同编号</el-button
                      >
                    </el-col>
                  </el-row>

                  <div class="form-section-title">出租方信息</div>
                  <div class="form-grid">
                    <el-row :gutter="16">
                      <el-col :span="12">
                        <el-form-item label="名称" prop="lessorName">
                          <el-input
                            disabled
                            v-model="contractForm.carrierInfo.lessorName"
                            placeholder="请输入出租方名称"
                          />
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="联系人" prop="lessorContactPerson">
                          <el-input
                            disabled
                            v-model="contractForm.carrierInfo.lessorContactPerson"
                            placeholder="请输入出租方联系人"
                          />
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="联系方式" prop="lessorContactInfo">
                          <el-input
                            disabled
                            v-model="contractForm.carrierInfo.lessorContactInfo"
                            placeholder="请输入出租方联系方式"
                          />
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="信用代码" prop="lessorCreditCode">
                          <el-input
                            disabled
                            v-model="contractForm.carrierInfo.lessorCreditCode"
                            placeholder="请输入出租方信用代码"
                          />
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="16">
                      <el-col :span="12">
                        <el-form-item label="企业地址" prop="lessorAddress">
                          <el-input
                            disabled
                            v-model="contractForm.carrierInfo.lessorAddress"
                            placeholder="请输入出租方企业地址"
                          />
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="开户行" prop="lessorBank">
                          <el-input
                            disabled
                            v-model="contractForm.carrierInfo.lessorBank"
                            placeholder="请输入出租方开户行"
                          />
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="银行账号" prop="lessorAccount">
                          <el-input
                            disabled
                            v-model="contractForm.carrierInfo.lessorAccount"
                            placeholder="请输入出租方账号"
                          />
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </div>

                  <div class="form-section-title">承租方信息</div>
                  <div class="form-grid">
                    <el-row :gutter="16">
                      <el-col :span="12">
                        <el-form-item label="名称" prop="lesseeName">
                          <el-input
                            v-model="contractForm.lesseeName"
                            placeholder="请输入承租方名称"
                          />
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="联系人" prop="lesseeContactPerson">
                          <el-input
                            v-model="contractForm.lesseeContactPerson"
                            placeholder="请输入承租方联系人"
                          />
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="联系方式" prop="lesseeContactInfo">
                          <el-input
                            v-model="contractForm.lesseeContactInfo"
                            placeholder="请输入承租方联系方式"
                          />
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="信用代码" prop="lesseeCreditCode">
                          <el-input
                            v-model="contractForm.lesseeCreditCode"
                            placeholder="请输入承租方信用代码"
                          />
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="16">
                      <el-col :span="12">
                        <el-form-item label="企业地址" prop="lesseeAddress">
                          <el-input
                            v-model="contractForm.lesseeAddress"
                            placeholder="请输入承租方企业地址"
                          />
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="开户行" prop="lesseeBank">
                          <el-input
                            v-model="contractForm.lesseeBank"
                            placeholder="请输入承租方开户行"
                          />
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="银行账号" prop="lesseeAccount">
                          <el-input
                            v-model="contractForm.lesseeAccount"
                            placeholder="请输入承租方账号"
                          />
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </div>
                  <el-divider>租赁物信息</el-divider>
                  <el-row :gutter="16">
                    <el-col :span="12">
                      <el-form-item label="项目地址" prop="address">
                        <el-input
                          v-model="contractForm.address"
                          placeholder="请输入项目地址"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="房号" prop="roomNumber">
                        <el-select
                          v-model="contractForm.roomNumber"
                          placeholder="请选择房号"
                          filterable
                          multiple
                          collapse-tags
                          collapse-tags-tooltip
                          style="width: 100%"
                          @change="handleRoomChange"
                        >
                          <el-option
                            v-for="item in freeRooms"
                            :key="item.id"
                            :label="`${item.zt} - ${
                              item.assetType === 0 ? '房间' : '工位'
                            }：${item.roomNumber}（${getRoomStatusText(item.status)}）`"
                            :value="item.roomNumber"
                            :disabled="isRoomDisabled(item)"
                          >
                            <span
                              :style="{ color: isRoomDisabled(item) ? '#c0c4cc' : '' }"
                            >
                              {{ item.zt }} -
                              {{ item.assetType === 0 ? "房间" : "工位" }}：{{
                                item.roomNumber
                              }}（{{ getRoomStatusText(item.status) }}）
                            </span>
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="16">
                    <el-col :span="8">
                      <el-form-item label="面积（m²）" prop="area">
                        <el-input
                          v-model="contractForm.area"
                          type="number"
                          min="0"
                          placeholder="请输入面积（m²）"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="租期（月）" prop="totalDuration">
                        <el-input
                          v-model="contractForm.totalDuration"
                          type="number"
                          min="1"
                          placeholder="请输入租期（月）"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="租赁期限" prop="leaseTerm">
                        <el-date-picker
                          v-model="leaseDateRange"
                          type="daterange"
                          validate-event
                          range-separator="至"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
                          format="YYYY年MM月DD日"
                          value-format="YYYY-MM-DD"
                          style="width: 100%"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="金额日期" prop="startTime">
                        <el-date-picker
                          v-model="contractForm.startTime"
                          type="date"
                          placeholder="请选择金额起算日期"
                          format="YYYY年MM月DD日"
                          value-format="YYYY-MM-DD"
                          style="width: 100%"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-divider>条款信息</el-divider>
                  <el-row :gutter="16">
                    <el-col :span="6">
                      <el-form-item label="免租期（月）" prop="rentFreePeriod">
                        <el-input
                          v-model="contractForm.rentFreePeriod"
                          type="number"
                          min="0"
                          placeholder="可不填，单位：月"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="租金单价(元)" prop="unitRentPrice">
                        <el-input
                          v-model="contractForm.unitRentPrice"
                          type="number"
                          min="0"
                          placeholder="请输入租金单价（元/m²）"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="物业类型" prop="propertyType">
                        <el-select
                          v-model="contractForm.propertyType"
                          placeholder="请选择"
                          disabled
                        >
                          <el-option label="自有物业" value="自有物业" />
                          <el-option label="第三方物业" value="第三方物业" />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6" v-if="contractForm.propertyType === '自有物业'">
                      <el-form-item label="物业费(元/月)" prop="amount">
                        <el-input
                          v-model="contractForm.amount"
                          type="number"
                          min="0"
                          placeholder="请输入物业费"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="保证金（元）" prop="securityDeposit">
                        <el-input
                          v-model="contractForm.securityDeposit"
                          type="number"
                          min="0"
                          placeholder="请输入保证金（元）"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="付款方式">
                        <div
                          style="
                            display: flex;
                            align-items: center;
                            gap: 8px;
                            width: 100%;
                          "
                        >
                          <span>付</span>
                          <el-input
                            v-model="payNum"
                            type="number"
                            min="1"
                            placeholder="付"
                            style="width: 80px"
                          />
                          <span>押</span>
                          <el-input
                            v-model="depositNum"
                            type="number"
                            min="0"
                            placeholder="押"
                            style="width: 80px"
                          />
                        </div>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="16">
                    <el-col :span="24">
                      <el-form-item label="备注" prop="remark">
                        <el-input
                          v-model="contractForm.remark"
                          type="textarea"
                          placeholder="请输入备注"
                        /> </el-form-item
                    ></el-col>
                  </el-row>
                  <el-row :gutter="16">
                    <el-col :span="4">
                      <span style="color: red; margin-right: 5px">*</span>
                      <el-button type="success" @click="handleDraftContract"
                        >信息保存</el-button
                      >
                    </el-col>
                  </el-row>
                </el-form>
                <el-card
                  v-if="contractForm.contractNumber && contractType != '虚拟'"
                  shadow="never"
                  style="margin: 24px 0; padding: 0"
                  body-style="padding: 0"
                >
                  <div
                    style="
                      display: flex;
                      justify-content: space-between;
                      align-items: center;
                      margin-bottom: 12px;
                    "
                  >
                    <span class="block-title">回款计划</span>
                    <el-button
                      type="primary"
                      @click="handleAddPlan"
                      v-if="!addRowVisible"
                      :disabled="contractForm.approvalNo"
                      >新增回款计划</el-button
                    >
                  </div>

                  <el-table :data="tableData" style="width: 100%">
                    <el-table-column label="缴费周期" width="320">
                      <template #default="scope">
                        <template v-if="editRow === scope.$index">
                          <el-date-picker
                            v-model="editForm.cycleStart"
                            type="date"
                            placeholder="开始日期"
                            format="YYYY年MM月DD日"
                            value-format="YYYY-MM-DD"
                            style="width: 45%"
                          />
                          <span
                            style="display: inline-block; text-align: center; width: 10%"
                            >至</span
                          >
                          <el-date-picker
                            v-model="editForm.cycleEnd"
                            type="date"
                            placeholder="结束日期"
                            format="YYYY年MM月DD日"
                            value-format="YYYY-MM-DD"
                            style="width: 45%"
                          />
                        </template>
                        <template v-else>
                          <span>{{ scope.row.cycle }}</span>
                        </template>
                      </template>
                    </el-table-column>
                    <el-table-column label="单价" width="120">
                      <template #default="scope">
                        <template v-if="editRow === scope.$index">
                          <el-input v-model="editForm.unitPrice" placeholder="单价" />
                        </template>
                        <template v-else>
                          <span>{{ scope.row.unitPrice }}</span>
                        </template>
                      </template>
                    </el-table-column>
                    <el-table-column label="月度费用" width="120">
                      <template #default="scope">
                        <template v-if="editRow === scope.$index">
                          <el-input
                            v-model="editForm.monthPrice"
                            placeholder="月度费用"
                          />
                        </template>
                        <template v-else>
                          <span>{{ scope.row.monthPrice }}</span>
                        </template>
                      </template>
                    </el-table-column>
                    <el-table-column label="起算日期" width="180">
                      <template #default="scope">
                        <template v-if="editRow === scope.$index">
                          <el-date-picker
                            v-model="editForm.startTime"
                            type="date"
                            placeholder="选择日期"
                            format="YYYY年MM月DD日"
                            value-format="YYYY年MM月DD日"
                            style="width: 100%"
                          />
                        </template>
                        <template v-else>
                          <span>{{ scope.row.startTime }}</span>
                        </template>
                      </template>
                    </el-table-column>
                    <el-table-column label="应缴费用金额" width="120">
                      <template #default="scope">
                        <template v-if="editRow === scope.$index">
                          <el-input
                            v-model="editForm.amount"
                            placeholder="应缴费用金额"
                          />
                        </template>
                        <template v-else>
                          <span>{{ scope.row.amount }}</span>
                        </template>
                      </template>
                    </el-table-column>
                    <el-table-column label="类型" width="120">
                      <template #default="scope">
                        <template v-if="editRow === scope.$index">
                          <el-select v-model="editForm.type" placeholder="请选择类型">
                            <el-option label="物业费" value="物业费" />
                            <el-option label="租金" value="租金" />
                            <el-option label="押金" value="押金" />
                            <el-option label="其他" value="其他" />
                          </el-select>
                        </template>
                        <template v-else>
                          <span>{{ scope.row.type }}</span>
                        </template>
                      </template>
                    </el-table-column>
                    <el-table-column label="备注">
                      <template #default="scope">
                        <template v-if="editRow === scope.$index">
                          <el-input v-model="editForm.remake" placeholder="备注" />
                        </template>
                        <template v-else>
                          <span>{{ scope.row.remake }}</span>
                        </template>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="180">
                      <template #default="scope">
                        <template v-if="editRow === scope.$index">
                          <el-button
                            type="success"
                            size="small"
                            :disabled="contractForm.approvalNo"
                            @click="handleSavePlan(scope.row)"
                            >保存</el-button
                          >
                          <el-button
                            type="info"
                            size="small"
                            :disabled="contractForm.approvalNo"
                            @click="handleCancelEdit(scope.$index)"
                            >取消</el-button
                          >
                        </template>
                        <template v-else>
                          <el-button
                            type="primary"
                            size="small"
                            :disabled="contractForm.approvalNo"
                            @click="handleEdit(scope.$index, scope.row)"
                            >编辑</el-button
                          >
                          <el-button
                            type="danger"
                            size="small"
                            :disabled="contractForm.approvalNo"
                            @click="handleDelete(scope.$index, scope.row)"
                            >删除</el-button
                          >
                        </template>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-card>
                <el-form :inline="true" label-width="110px" label-position="top">
                  <span
                    style="color: red; margin-right: 5px"
                    v-if="contractForm.contractNumber"
                    >*</span
                  ><el-button
                    type="primary"
                    @click="handleCreatedDraftContract"
                    v-if="contractForm.contractNumber"
                    >生成合同</el-button
                  >
                  <el-form-item>
                    <span style="text-align: center; margin-top: 5px; margin-left: 5px"
                      >会签人:</span
                    >
                  </el-form-item>
                  <el-form-item>
                    <el-select
                      v-model="contractForm.counterSignUsers"
                      multiple
                      filterable
                      remote
                      reserve-keyword
                      placeholder="请输入用户名搜索"
                      :remote-method="handleCounterSignUserSearch"
                      :loading="counterSignUsersLoading"
                      style="width: 220px"
                      :remote-show-suffix="true"
                      @visible-change="handleCounterSignUserVisibleChange"
                    >
                      <div
                        style="max-height: 200px; overflow-y: auto"
                        @scroll.passive="handleCounterSignUserScroll"
                      >
                        <el-option
                          v-for="item in counterSignUsers"
                          :key="item.userId"
                          :label="item.nickName"
                          :value="item.userId"
                        />
                      </div>
                    </el-select>
                  </el-form-item>
                  <el-form-item>
                    <span style="color: red; margin-right: 5px">*</span
                    ><el-button
                      type="success"
                      :disabled="contractForm.approvalNo"
                      @click="createFeiShuSealTaskBtn"
                      v-if="contractForm.contractNumber"
                      >发起飞书用印审批</el-button
                    >
                    <div
                      v-if="contractForm.approvalNo"
                      style="color: red; position: absolute; top: 35px; left: 0"
                    >
                      已创建飞书流程，当前状态：{{
                        contractForm.approvalStatus == "ERROR"
                          ? "创建失败"
                          : contractForm.approvalStatus == "PENDING"
                          ? "审批中"
                          : "通过"
                      }}
                    </div>
                  </el-form-item>
                </el-form>
              </el-card>
              <!-- 虚拟表单 -->
              <el-card
                v-if="contractType === '虚拟'"
                class="material-block"
                shadow="never"
                body-style="width: 100%; "
                style="max-width: 100%; min-width: 400px"
              >
                <div class="block-title">合同拟定（虚拟）</div>
                <el-form
                  :model="contractForm"
                  ref="contractFormRef"
                  label-width="110px"
                  :disabled="contractForm.approvalNo"
                  label-position="left"
                >
                  <el-row :gutter="16">
                    <el-col :span="12">
                      <el-form-item label="合同编号" prop="contractNumber">
                        <el-input
                          v-model="contractForm.contractNumber"
                          placeholder="合同编号（自动生成）"
                          disabled
                          style="width: calc(100% - 120px); display: inline-block"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item>
                        <span
                          v-if="!contractForm.contractNumber && !contractForm.id"
                          style="color: red; margin-right: 5px"
                          >*</span
                        >
                        <el-button
                          v-if="!contractForm.contractNumber"
                          type="primary"
                          style="margin-left: 8px; vertical-align: top"
                          @click="handleGenerateContractNumber"
                          >生成合同编号</el-button
                        >
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-divider>出租方信息</el-divider>
                  <el-row :gutter="16">
                    <el-col :span="24">
                      <el-form-item label="名称" prop="lessorName">
                        <el-input
                          v-model="contractForm.carrierInfo.lessorName"
                          placeholder="请输入出租方名称"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-divider>承租方信息</el-divider>
                  <el-row :gutter="16">
                    <el-col :span="24">
                      <el-form-item label="名称" prop="lesseeName">
                        <el-input
                          v-model="contractForm.lesseeName"
                          placeholder="请输入承租方名称"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-divider>租赁物信息</el-divider>
                  <el-row :gutter="16">
                    <el-col :span="12">
                      <el-form-item label="项目地址" prop="address">
                        <el-input
                          v-model="contractForm.address"
                          placeholder="请输入项目地址"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="房号" prop="roomNumber">
                        <el-select
                          v-model="contractForm.roomNumber"
                          placeholder="请选择房号"
                          filterable
                          multiple
                          collapse-tags
                          collapse-tags-tooltip
                          style="width: 100%"
                          @change="handleRoomChange"
                        >
                          <el-option
                            v-for="item in freeRooms"
                            :key="item.id"
                            :label="`${item.zt} - ${
                              item.assetType === 0 ? '房间' : '工位'
                            }：${item.roomNumber}（${getRoomStatusText(item.status)}）`"
                            :value="item.roomNumber"
                          >
                            <span>
                              {{ item.zt }} -
                              {{ item.assetType === 0 ? "房间" : "工位" }}：{{
                                item.roomNumber
                              }}（{{ getRoomStatusText(item.status) }}）
                            </span>
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="16">
                    <el-col :span="8">
                      <el-form-item label="面积" prop="area">
                        <el-input
                          v-model="contractForm.area"
                          type="number"
                          min="0"
                          placeholder="请输入面积"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="租赁年限" prop="year">
                        <el-input
                          v-model="contractForm.year"
                          type="number"
                          min="1"
                          placeholder="请输入租赁年限（年）"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="16">
                    <el-col :span="12">
                      <el-form-item label="租赁期限" prop="leaseTerm">
                        <el-date-picker
                          v-model="leaseDateRange_start"
                          type="date"
                          placeholder="请选择租赁开始日期"
                          format="YYYY年MM月DD日"
                          value-format="YYYY-MM-DD"
                          style="width: 100%"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="金额" prop="amount">
                        <el-input
                          v-model="contractForm.amount"
                          type="number"
                          min="0"
                          placeholder="请输入金额"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="16">
                    <el-col :span="24">
                      <el-form-item label="其他约定事项" prop="message">
                        <el-input
                          v-model="contractForm.message"
                          type="textarea"
                          placeholder="请输入其他约定事项"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="16">
                    <el-col :span="24">
                      <el-form-item label="备注" prop="remark">
                        <el-input
                          v-model="contractForm.remark"
                          type="textarea"
                          placeholder="请输入备注"
                        /> </el-form-item
                    ></el-col>
                  </el-row>

                  <el-row :gutter="16">
                    <el-col :span="4">
                      <span style="color: red; margin-right: 5px">*</span>
                      <el-button type="success" @click="handleDraftContract"
                        >信息保存</el-button
                      >
                    </el-col>
                    <el-col :span="4">
                      <el-form-item>
                        <span
                          style="color: red; margin-right: 5px"
                          v-if="contractForm.contractNumber"
                          >*</span
                        >
                        <el-button
                          type="primary"
                          @click="handleCreatedDraftContract"
                          v-if="contractForm.id"
                          >生成合同</el-button
                        >
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </el-card>
            </div>
            <!-- 步骤操作按钮 -->
            <div style="margin-top: 32px; display: flex; gap: 16px">
              <el-button @click="handlePrevStep" :disabled="activeStep === 0"
                >上一步</el-button
              >
              <el-button
                @click="handleNextStep"
                v-if="isRehandleCertificate"
                :disabled="activeStep === steps.length - 1"
                >下一步</el-button
              >
              <el-button
                v-if="route.query.companyStatus != 7 && !isRehandleCertificate"
                type="success"
                :disabled="!contractForm.id"
                @click="handleCompletePropertyStep"
              >
                完成当前流程
              </el-button>
            </div>
          </div>
          <div v-show="activeStep === 1">
            <div
              style="
                display: flex;
                gap: 24px;
                justify-content: space-between;
                flex-wrap: wrap;
              "
            >
              <el-card class="material-block" shadow="never">
                <div class="block-title">办证材料</div>
                <div class="material-inner-row">
                  <div class="upload-vertical">
                    <div class="upload-section">
                      <div class="upload-label">法人签字笔迹</div>
                      <el-upload
                        class="upload-demo"
                        :show-file-list="true"
                        :auto-upload="true"
                        :file-list="fileListSign"
                        :before-upload="(file) => beforeUpload(file, 2)"
                        :on-preview="(file) => handleFilePreview(file, 'sign')"
                        :on-remove="(file) => handleFileRemove('sign', file)"
                        :multiple="true"
                        accept="image/*"
                      >
                        <el-button type="primary">上传法人签字笔迹</el-button>
                      </el-upload>
                    </div>
                    <div class="upload-section">
                      <div class="upload-label">自然人身份证</div>
                      <el-upload
                        class="upload-demo"
                        :show-file-list="true"
                        :auto-upload="true"
                        :file-list="fileListId"
                        :before-upload="(file) => beforeUpload(file, 3)"
                        :on-preview="(file) => handleFilePreview(file, 'id')"
                        :on-remove="(file) => handleFileRemove('id', file)"
                        :multiple="true"
                        accept="image/*"
                      >
                        <el-button type="primary">上传自然人身份证</el-button>
                      </el-upload>
                    </div>
                    <div class="upload-section">
                      <div class="upload-label">非自然人营业执照</div>
                      <el-upload
                        class="upload-demo"
                        :show-file-list="true"
                        :auto-upload="true"
                        :file-list="fileListLicense"
                        :before-upload="(file) => beforeUpload(file, 4)"
                        :on-preview="(file) => handleFilePreview(file, 'license')"
                        :on-remove="(file) => handleFileRemove('license', file)"
                        :multiple="true"
                        accept="image/*"
                      >
                        <el-button type="primary">上传非自然人营业执照</el-button>
                      </el-upload>
                    </div>
                  </div>
                </div>
              </el-card>
              <el-card class="material-block" shadow="never" style="margin-bottom: 18px">
                <div class="block-title">办证模块</div>
                <div
                  class="material-inner-row"
                  style="display: flex; align-items: center; flex-wrap: wrap; gap: 24px"
                >
                  <div class="upload-vertical">
                    <div class="upload-section">
                      <div class="upload-label">营业执照</div>
                      <el-upload
                        class="upload-demo"
                        :show-file-list="true"
                        :auto-upload="true"
                        :file-list="fileListLicensePdf"
                        :before-upload="(file) => beforeUpload(file, 12)"
                        :on-change="(f, fl) => handleFileChange('licensePdf', f, fl)"
                        :on-preview="(file) => handleFilePreview(file, 'licensePdf')"
                        :on-remove="(file) => handleFileRemove('licensePdf', file)"
                        accept="*"
                        list-type="text"
                      >
                        <el-button type="primary">上传营业执照</el-button>
                      </el-upload>
                    </div>
                  </div>
                  <div class="block-img">
                    <img
                      :src="banzhengliuch"
                      alt="办证流程"
                      class="img-clickable full-img"
                      @click="handleFilePreview(banzhengliuch, '示例图')"
                    />
                    <div class="example-label">办证流程</div>
                  </div>
                </div>
              </el-card>
            </div>
            <div style="margin-top: 32px; display: flex; gap: 16px">
              <el-button @click="handlePrevStep" :disabled="activeStep === 0"
                >上一步</el-button
              >
              <el-button
                @click="handleNextStep"
                :disabled="activeStep === steps.length - 1"
                >下一步</el-button
              ><el-button
                v-if="route.query.companyStatus != 7 && isRehandleCertificate"
                type="success"
                :disabled="!contractForm.id && fileListLicensePdf.length === 0"
                @click="handleCompletePropertyStep"
              >
                完成当前流程
              </el-button>
            </div>
          </div>
        </div>
      </div>
      <!-- 文件预览弹窗 -->
      <el-dialog
        v-model="previewDialogVisible"
        :title="'文件预览：' + previewFileName"
        width="60vw"
        top="5vh"
        :close-on-click-modal="false"
      >
        <template v-if="previewFileType === 'image'">
          <img :src="previewFileUrl" alt="" style="width: 55vw" />
        </template>
        <template v-else-if="previewFileType === 'pdf'">
          <iframe :src="previewFileUrl" style="width: 100%; height: 70vh; border: none" />
        </template>
        <template v-else-if="previewFileType === 'word'">
          <iframe
            :src="
              'https://view.officeapps.live.com/op/view.aspx?src=' +
              encodeURIComponent(previewFileUrl)
            "
            style="width: 100%; height: 70vh; border: none"
          />
        </template>
        <template v-else-if="previewFileType === 'excel'">
          <iframe
            :src="
              'https://view.officeapps.live.com/op/view.aspx?src=' +
              encodeURIComponent(previewFileUrl)
            "
            style="width: 100%; height: 70vh; border: none"
          />
        </template>
        <template v-else>
          <el-alert
            type="warning"
            :closable="false"
            title="暂不支持此类型文件在线预览，可下载后本地打开。"
          />
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, watch, computed, getCurrentInstance } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { bindRoom } from "@/api/property/index.js"; // 绑定房间号
import banzhengliuch from "@/assets/banzhengliuch.png";
import { updateCertification } from "@/api/certificate/index.js";

import {
  getDraftContract,
  createDraftContract,
  updateDraftContract,
  generateContractNumber,
  getCarrierInfo,
  generateWord,
  getPaymentPlanList,
  addPaymentPlan,
  updatePaymentPlan,
  companyUploadFile,
  getFileByCompanyIdAndTag,
  deleteFile,
  submitFeiShuApproval,
  getFeiShuApprovalTaskMessage,
  submitAndUpdate,
} from "@/api/company/index";
import {
  getPaymentPlanList as getPaymentPlanListNew,
  createFeiShuSealTask,
  DraftContractEnd,
  listForUser,
} from "@/api/company/info";
import { getAllRoomList } from "@/api/property/index";
// 旧合同相关
const oldContractInfo = ref(null);
const oldContractPlans = ref([]);
const editOldRow = ref(-1);
const addOldRowVisible = ref(false);
const editOldForm = ref({});
// 会签人员相关数据
const counterSignUsers = ref([]);
const counterSignUsersLoading = ref(false);
const counterSignUserPage = ref(1);
const counterSignUserPageSize = ref(20);
const counterSignUserTotal = ref(0);
const counterSignUserSearch = ref("");
// 获取会签人员列表
const loadCounterSignUsers = async (reset = false) => {
  if (reset) {
    counterSignUserPage.value = 1;
    counterSignUsers.value = [];
  }

  counterSignUsersLoading.value = true;

  try {
    const params = {
      pageNum: counterSignUserPage.value,
      pageSize: counterSignUserPageSize.value,
      nickName: counterSignUserSearch.value,
    };

    const response = await listForUser(params);
    const { rows, total } = response;

    if (reset) {
      counterSignUsers.value = rows;
    } else {
      counterSignUsers.value = [...counterSignUsers.value, ...rows];
    }

    counterSignUserTotal.value = total;
  } catch (error) {
    console.error("获取会签人员列表失败:", error);
  } finally {
    counterSignUsersLoading.value = false;
  }
};

// 防抖函数
const debounce = (func, wait) => {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
};

// 搜索会签人员（带防抖）
const handleCounterSignUserSearch = debounce((query) => {
  counterSignUserSearch.value = query;
  loadCounterSignUsers(true);
}, 300);

// 滚动加载更多会签人员
const handleCounterSignUserScroll = (e) => {
  const { scrollTop, clientHeight, scrollHeight } = e.target;
  // 当滚动到底部且还有更多数据时加载更多
  if (scrollTop + clientHeight >= scrollHeight - 10 && !counterSignUsersLoading.value) {
    if (counterSignUsers.value.length < counterSignUserTotal.value) {
      counterSignUserPage.value++;
      loadCounterSignUsers();
    }
  }
};

// 当下拉框可见性改变时触发
const handleCounterSignUserVisibleChange = (visible) => {
  if (visible && counterSignUsers.value.length === 0) {
    // 当下拉框首次打开且还没有数据时加载数据
    loadCounterSignUsers(true);
  }
};

// 调用飞书用印接口
function createFeiShuSealTaskBtn() {
  createFeiShuSealTask({
    contractNumber: contractForm.value.contractNumber,
    // nickName: contractForm.value.counterSignUsers[0].nickName,
    userId: contractForm.value.counterSignUsers,
  })
    .then((res) => {
      ElMessage.success("飞书用印申请已提交，请前往飞书审批中查看结果");
    })
    .catch((err) => {
      ElMessage.error("飞书用印申请提交失败");
    });
}
// 旧合同回款计划操作

function handleAddOldPlan() {
  addOldRowVisible.value = true;
  editOldRow.value = oldContractPlans.value.length;
  editOldForm.value = {
    contractNumber: oldContractInfo.value.contractNumber,
    cycleStart: "",
    cycleEnd: "",
    startTime: "",
    unitPrice: "",
    monthPrice: "",
    amount: "",
    paidAmount: "",
    remainingAmount: "",
    type: "",
    remake: "",
  };
  oldContractPlans.value.push({ ...editOldForm.value });
}

function handleEditOldPlan(index, row) {
  editOldRow.value = index;
  addOldRowVisible.value = false;
  // 拆分cycle为cycleStart/cycleEnd，兼容老数据
  let cycleStart = "";
  let cycleEnd = "";
  if (row.cycle && row.cycle.includes("至")) {
    [cycleStart, cycleEnd] = row.cycle.split("至").map((s) => s.trim());
  }
  editOldForm.value = {
    ...row,
    cycleStart: row.cycleStart || cycleStart,
    cycleEnd: row.cycleEnd || cycleEnd,
    startTime: row.startTime || "",
  };
}

function handleCancelOldEdit() {
  if (addOldRowVisible.value) oldContractPlans.value.pop();
  editOldRow.value = -1;
  addOldRowVisible.value = false;
}

async function handleSaveOldPlan(index) {
  // 合并cycleStart/cycleEnd为cycle
  const cycle =
    editOldForm.value.cycleStart && editOldForm.value.cycleEnd
      ? `${editOldForm.value.cycleStart} 至 ${editOldForm.value.cycleEnd}`
      : "";
  const submitData = {
    ...editOldForm.value,
    contractNumber: oldContractInfo.value.contractNumber,
    cycle,
    remainingAmount: editOldForm.value.amount, // 默认剩余金额=应缴金额
  };
  try {
    if (submitData.id) {
      await updatePaymentPlan({ ...submitData, flag: 0 });
    } else {
      await addPaymentPlan(submitData);
    }
    proxy.$modal.msgSuccess("保存成功");
    editOldRow.value = -1;
    addOldRowVisible.value = false;
    fetchOldContractInfo(oldContractInfo.value.contractNumber);
  } catch (e) {
    console.log("保存失败", e);
  }
}

async function handleDeleteOldPlan(index, row) {
  if (!row.id) {
    oldContractPlans.value.splice(index, 1);
    return;
  }
  try {
    await updatePaymentPlan({ ...row, flag: 1 });
    proxy.$modal.msgSuccess("删除成功");
    fetchOldContractInfo(oldContractInfo.value.contractNumber);
  } catch (e) {
    console.log("删除失败");
  }
}

// 办证材料
const fileListSign = ref([]);
const fileListId = ref([]);
const fileListLicense = ref([]);

const steps = ref([{ title: "合同" }, { title: "办证" }]);

const { proxy } = getCurrentInstance();
const route = useRoute();
const router = useRouter();

const isRehandleCertificate = computed(() => route.query.isRehandleCertificate == 1);
const activeStep = ref(0);

// Global
const companyClass = ref("");
const carrieType = ref("");

// Step 0: Contract
const contractType = ref("孵化器");
const payNum = ref("1");
const depositNum = ref("1");
const leaseDateRange = ref([]);
const leaseDateRange_start = ref("");
const leaseYears = ref("");
const contractFormRef = ref();
const freeRooms = ref([]);
const tableData = ref([]);
const editRow = ref(-1);
const addRowVisible = ref(false);
const editForm = ref({});
const fileListContractArchive = ref([]);
const fileListVirtualArchive = ref([]);
const sealType = ref("实体章");
const createTimeSeal = ref(new Date());
const approvalNumber = ref("");
const sealVirtualType = ref("实体章");
const createTimeVirtual = ref(new Date());
const approvalVirtualNumber = ref("");
const isContractSealDisabled = ref(false);

const contractForm = ref({
  type: contractType.value,
  companyId: route.query.companyId || route.params.companyId || "",
  contractNumber: "",
  carrierName: "",
  carrierInfo: {
    lessorName: "",
    lessorContactPerson: "",
    lessorContactInfo: "",
    lessorCreditCode: "",
    lessorAddress: "",
    lessorBank: "",
    lessorAccount: "",
  },
  lesseeName: "",
  lesseeContactPerson: "",
  lesseeContactInfo: "",
  lesseeCreditCode: "",
  lesseeAddress: "",
  lesseeBank: "",
  lesseeAccount: "",
  address: "",
  roomNumber: [],
  roomId: "",
  area: "",
  leaseTerm: "",
  rentFreePeriod: "",
  unitRentPrice: "",
  propertyType: "自有物业",
  paymentTerms: "",
  securityDeposit: "",
  amount: "",
  waterExpense: "",
  electricityExpense: "",
  level: "",
  year: "",
  message: "",
  lessorName: "",
});

const contractRules = {
  remark: [{ required: true, message: "备注必填", trigger: "blur" }],

  lesseeName: [{ required: true, message: "承租方名称必填", trigger: "blur" }],
  lesseeContactPerson: [{ required: true, message: "承租方联系人必填", trigger: "blur" }],
  lesseeContactInfo: [{ required: true, message: "承租方联系方式必填", trigger: "blur" }],
  address: [{ required: true, message: "项目地址必填", trigger: "blur" }],
  roomNumber: [
    {
      required: true,
      message: "房号必填",
      trigger: "change",
      type: "array",
      min: 1,
    },
  ],
  area: [{ required: true, message: "面积必填", trigger: "blur" }],
  leaseTerm: [
    {
      required: true,
      message: "租赁期限必填",
      trigger: "blur",
      validator: (rule, value, callback) => {
        callback();
      },
    },
  ],
  unitRentPrice: [{ required: true, message: "租金单价必填", trigger: "blur" }],
  propertyType: [{ required: true, message: "物业类型必填", trigger: "change" }],
  securityDeposit: [{ required: true, message: "保证金必填", trigger: "blur" }],
};

// Preview Dialog
const previewDialogVisible = ref(false);
const previewFileType = ref("");
const previewFileUrl = ref("");
const previewFileName = ref("");

// --- METHODS ---

function goStep(index) {
  if (!isRehandleCertificate.value && index > 0) {
    return;
  }
  activeStep.value = index;
}

function handleStepChange(newStep) {
  goStep(newStep);
}

function handlePrevStep() {
  if (activeStep.value > 0) {
    activeStep.value--;
  }
}

function handleNextStep() {
  const maxStep = isRehandleCertificate.value ? 2 : 0;
  if (activeStep.value < maxStep) {
    activeStep.value++;
  }
}
// 上传前处理，调用companyUploadFile接口
async function beforeUpload(file, tag) {
  const companyId = route.query.companyId || route.params.companyId;
  const formData_company = new FormData();
  formData_company.append("companyId", companyId);
  formData_company.append("processId", route.query.processId);

  formData_company.append("file", file);
  formData_company.append("tag", tag);
  try {
    const res = await companyUploadFile(formData_company);
    // 上传成功后刷新文件列表
    await refreshFileListByTag(tag);
    if (tag == 12) {
      await updateCertification({ companyId: companyId, certificationStatus: 2 });
    }
    return false; // 阻止el-upload默认上传
  } catch (e) {
    console.error("上传失败", e);
    return false;
  }
}

// 刷新单个tag的文件列表
async function refreshFileListByTag(tag) {
  const companyId = route.query.companyId || route.params.companyId;
  const params = {
    pageNum: 1,
    pageSize: 20,
    companyId,
    tag,
    processId: route.query.processId,
  };
  try {
    const res = await getFileByCompanyIdAndTag(params);
    const files = (res && res.rows ? res.rows : []).map((f) => ({
      id: f.id,
      name: f.fileName || "",
      url: f.url,
    }));
    if (tag === 0) fileListRecord.value = files;
    else if (tag === 13) fileListRecordOk.value = files;
    else if (tag === 1) fileListInfo.value = files;
    else if (tag === 2) fileListSign.value = files;
    else if (tag === 3) fileListId.value = files;
    else if (tag === 4) fileListLicense.value = files;
    else if (tag === 7) fileListContractArchive.value = files;
    else if (tag === 14) fileListVirtualArchive.value = files;
    else if (tag === 15) fileListBeforeDecoration.value = files;
    else if (tag === 16) fileListAfterDecoration.value = files;
    else if (tag === 9) fileListPropertyHandover.value = files;
    else if (tag === 11) fileListPlanPdf.value = files;
    else if (tag === 19) fileListPlanZip.value = files;
    else if (tag === 17) fileListWaterMeter.value = files;
    else if (tag === 18) fileListElectricMeter.value = files;
    else if (tag === 12) fileListLicensePdf.value = files;
  } catch (e) {
    console.error("文件刷新失败", e);
  }
}

// 删除文件
async function handleFileRemove(type, file) {
  if (!file.id) {
    // 归档文件上传后el-upload会自动触发on-remove，临时文件无id，直接忽略不报错
    return;
  }
  try {
    await deleteFile({ id: file.id });
    // 删除后刷新对应tag的文件列表
    let tag = 0;
    if (type === "record") tag = 0;
    else if (type === "record_ok") tag = 13;
    else if (type === "info") tag = 1;
    else if (type === "sign") tag = 2;
    else if (type === "id") tag = 3;
    else if (type === "license") tag = 4;
    else if (type === "contractArchive") tag = 7;
    else if (type === "virtualArchive") tag = 14;
    await refreshFileListByTag(tag);
    proxy.$modal.msgSuccess("删除成功");
  } catch (e) {
    console.error("删除文件失败:", e);
  }
}
const fileListBeforeDecoration = ref([]);
const fileListAfterDecoration = ref([]);
const fileListPropertyHandover = ref([]);
const fileListPlanPdf = ref([]);
const fileListPlanZip = ref([]);
const fileListWaterMeter = ref([]);
const fileListElectricMeter = ref([]);
const fileListLicensePdf = ref([]);
// 合同归档文件上传/预览/删除复用原有逻辑
function handleFileChange(type, file, fileListArr) {
  if (type === "record") fileListRecord.value = fileListArr;
  if (type === "record_ok") fileListRecordOk.value = fileListArr;

  if (type === "info") fileListInfo.value = fileListArr;
  if (type === "sign") fileListSign.value = fileListArr;
  if (type === "id") fileListId.value = fileListArr;
  if (type === "license") fileListLicense.value = fileListArr;
  if (type === "contractArchive") fileListContractArchive.value = fileListArr;
  if (type === "virtualArchive") fileListVirtualArchive.value = fileListArr;
  if (type === "beforeDecoration") fileListBeforeDecoration.value = fileListArr;
  if (type === "afterDecoration") fileListAfterDecoration.value = fileListArr;
  if (type === "propertyHandover") fileListPropertyHandover.value = fileListArr;
  if (type === "planPdf") fileListPlanPdf.value = fileListArr;
  if (type === "planZip") fileListPlanZip.value = fileListArr;
  if (type === "waterMeter") fileListWaterMeter.value = fileListArr;
  if (type === "electricMeter") fileListElectricMeter.value = fileListArr;
  if (type === "licensePdf") fileListLicensePdf.value = fileListArr;
}
// 合同归档文件回显
async function refreshFileListContractArchive() {
  const companyId = route.query.companyId || route.params.companyId;
  const params = {
    pageNum: 1,
    pageSize: 20,
    companyId,
    tag: 7,
    processId: route.query.processId,
  };
  // 先清空，避免el-upload混入本地临时文件
  fileListContractArchive.value = [];

  try {
    const res = await getFileByCompanyIdAndTag(params);
    // el-upload 需要的file-list格式：{name, url, status, uid}
    const files = (res && res.rows ? res.rows : []).map((f, idx) => ({
      id: f.id,
      name: f.fileName || "",
      url: f.url,
      status: "done",
      uid: f.id ? String(f.id) : String(Date.now()) + "_" + idx,
    }));
    fileListContractArchive.value = files;
  } catch (e) {
    console.error("合同归档文件回显失败", e);
  }
}
// 合同归档文件回显
async function refreshFileListVirtualArchive() {
  const companyId = route.query.companyId || route.params.companyId;
  const params = {
    pageNum: 1,
    pageSize: 20,
    companyId,
    tag: 14,
    processId: route.query.processId,
  };
  // 先清空，避免el-upload混入本地临时文件
  fileListVirtualArchive.value = [];

  try {
    const res = await getFileByCompanyIdAndTag(params);
    // el-upload 需要的file-list格式：{name, url, status, uid}
    const files = (res && res.rows ? res.rows : []).map((f, idx) => ({
      id: f.id,
      name: f.fileName || "",
      url: f.url,
      status: "done",
      uid: f.id ? String(f.id) : String(Date.now()) + "_" + idx,
    }));
    fileListVirtualArchive.value = files;
  } catch (e) {
    console.log("handleFileList", e);
  }
}

function handleFilePreview(file, type) {
  console.log("handleFilePreview", file, type);

  // file.url需为可访问的文件地址
  let url =
    type == "示例图"
      ? file
      : file.url ||
        file.response.data.url || // 添加对 response.data.url 的支持
        file.response.url ||
        file.preview ||
        (file.raw && URL.createObjectURL(file.raw)) ||
        "";

  // 确保 url 是字符串类型
  if (typeof url !== "string") {
    url = "";
  }

  if (!url) {
    ElMessage && ElMessage.warning
      ? ElMessage.warning("文件地址无效")
      : proxy.$modal.msgWarning("文件地址无效");
    return;
  }

  previewFileUrl.value = url;
  previewFileName.value = file.name || file.fileName || "";

  // 判断文件类型
  const fileName =
    file.name ||
    file.fileName ||
    (typeof url === "string" ? url.split("/").pop() : "") ||
    "";
  const ext = fileName.split(".").pop().toLowerCase();

  if (["jpg", "jpeg", "png", "gif", "bmp", "webp"].includes(ext)) {
    previewFileType.value = "image";
  } else if (ext === "pdf") {
    previewFileType.value = "pdf";
  } else if (["doc", "docx"].includes(ext)) {
    previewFileType.value = "word";
  } else if (["xls", "xlsx"].includes(ext)) {
    previewFileType.value = "excel";
  } else {
    previewFileType.value = "other";
  }

  console.log("Preview file type:", previewFileType.value);
  previewDialogVisible.value = true;
}
// Contract Logic
async function handleGenerateContractNumber() {
  const companyId = contractForm.value.companyId;
  if (!companyId) {
    proxy.$modal.msgWarning("请先选择公司");
    return;
  }
  try {
    const res = await generateContractNumber({ companyId });
    contractForm.value.contractNumber = res.data;
    proxy.$modal.msgSuccess("合同编号生成成功");
  } catch (e) {
    console.error("生成合同编号失败", e);
  }
}

function handleTabChange(tab) {
  contractType.value = tab.paneName;
  resetContractForm();
  getCarrierInfoData();
  fetchFreeRooms();
}

function handleDraftContract() {
  contractFormRef.value.validate(async (valid) => {
    if (!valid) return;

    // Lease term validation
    if (contractType.value === "虚拟") {
      if (!leaseDateRange_start.value) return proxy.$modal.msgWarning("请选择租赁期限");
    } else {
      if (!leaseDateRange.value || leaseDateRange.value.length !== 2)
        return proxy.$modal.msgWarning("请选择租赁期限");
    }
    if (
      contractType.value === "孵化器" &&
      (!leaseYears.value || Number(leaseYears.value) <= 0)
    ) {
      return proxy.$modal.msgWarning("请输入有效的租赁年限");
    }

    // Format leaseTerm
    const formatDateToCN = (dateStr) => {
      if (!dateStr) return "";
      const d = new Date(dateStr.replace(/-/g, "/"));
      return `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日`;
    };

    if (contractType.value === "加速器") {
      const [start, end] = leaseDateRange.value.map(formatDateToCN);
      contractForm.value.leaseTerm = `自${start}起至${end}止`;
    } else if (contractType.value === "孵化器") {
      const [start, end] = leaseDateRange.value.map(formatDateToCN);
      contractForm.value.leaseTerm = `自${start}起至${end}止，共计${leaseYears.value}年。`;
    } else if (contractType.value === "虚拟") {
      const start = formatDateToCN(leaseDateRange_start.value);
      contractForm.value.leaseTerm = `该房屋租赁期${contractForm.value.year}年。自${start}起`;
    }

    // Format paymentTerms
    contractForm.value.paymentTerms = `付${payNum.value}押${depositNum.value}`;
    contractForm.value.processId = route.query.processId || route.params.processId || "";
    const payload = { ...contractForm.value, type: contractType.value };
    delete payload.roomNumber;

    try {
      if (payload.id) {
        await updateDraftContract(payload);
        proxy.$modal.msgSuccess("合同信息更新成功！");
      } else {
        await createDraftContract(payload);
        proxy.$modal.msgSuccess("合同信息保存成功！");
      }
      bindRoomNumber(payload);
      getCarrierInfoData();
    } catch (err) {
      console.error("合同信息保存失败", err);
    }
  });
}
//
async function handleCreatedDraftContract() {
  try {
    const res = await generateWord({
      contractNumber: contractForm.value.contractNumber,
    });
    const link = document.createElement("a");
    link.href = res.data;
    link.setAttribute("download", `${contractForm.value.contractNumber}.docx`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    proxy.$modal.msgSuccess("合同生成成功！");
  } catch (err) {
    console.error("合同生成失败，请稍后重试！", err);
  }
}

function handleRoomChange(roomNumbers) {
  const selectedRoomIds = roomNumbers
    .map((roomNumber) => {
      const room = freeRooms.value.find((r) => r.roomNumber === roomNumber);
      return room ? room.id : null;
    })
    .filter((id) => id !== null);
  contractForm.value.roomId = selectedRoomIds.join(",");
}

async function bindRoomNumber(data) {
  try {
    await bindRoom({ ...data, roomId: data.roomId });
  } catch (err) {
    console.error("绑定房间号失败", err);
  }
}

// Payment Plan Table
async function fetchPlanList() {
  if (!contractForm.value.contractNumber) return;
  const res = await getPaymentPlanListNew({
    pageNum: 1,
    pageSize: 100,
    contractNumber: contractForm.value.contractNumber,
  });
  tableData.value = res.rows || [];
}

function handleAddPlan() {
  addRowVisible.value = true;
  editRow.value = tableData.value.length;
  editForm.value = {
    contractNumber: contractForm.value.contractNumber,
    cycleStart: "",
    cycleEnd: "",
    unitPrice: "",
    monthPrice: "",
    startTime: "",
    amount: "",
    remake: "",
    type: "",
  };
  tableData.value.push({ ...editForm.value });
}

function handleEdit(index, row) {
  editRow.value = index;
  addRowVisible.value = false;
  editForm.value = { ...row };
}

function handleCancelEdit() {
  if (addRowVisible.value) tableData.value.pop();
  editRow.value = -1;
  addRowVisible.value = false;
}

async function handleSavePlan() {
  const formatDateToCN = (dateStr) => {
    if (!dateStr) return "";
    const date = new Date(dateStr);
    return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
  };
  const cycle =
    editForm.value.cycleStart && editForm.value.cycleEnd
      ? `${formatDateToCN(editForm.value.cycleStart)}起至${formatDateToCN(
          editForm.value.cycleEnd
        )}`
      : "";

  const submitData = {
    ...editForm.value,
    cycle,
    remainingAmount: editForm.value.amount,
    processId: route.query.processId || "",
  };
  delete submitData.cycleStart;
  delete submitData.cycleEnd;

  try {
    if (submitData.id) {
      await updatePaymentPlan({ ...submitData, flag: 0 });
    } else {
      await addPaymentPlan(submitData);
    }
    proxy.$modal.msgSuccess("保存成功");
    editRow.value = -1;
    addRowVisible.value = false;
    fetchPlanList();
  } catch (e) {
    console.error("保存失败", e);
  }
}

async function handleDelete(index, row) {
  if (!row.id) {
    tableData.value.splice(index, 1);
    return;
  }
  try {
    await updatePaymentPlan({
      ...row,
      flag: 1,
      processId: route.query.processId || "",
    });
    proxy.$modal.msgSuccess("删除成功");
    fetchPlanList();
  } catch {
    console.error("删除失败");
  }
}

// Seal Logic
function saveSealData(type) {
  const isVirtual = type === "虚拟";
  const seal = isVirtual ? sealVirtualType.value : sealType.value;
  const approvalNo = isVirtual ? approvalVirtualNumber.value : approvalNumber.value;
  const createTime = isVirtual ? createTimeVirtual.value : createTimeSeal.value;
  if (!approvalNo || !createTime) {
    proxy.$modal.msgWarning("请完善用印审批信息");
    return;
  }
  submitFeiShuApproval({
    type: "签章",
    contractNumber: contractForm.value.contractNumber,
    approvalType: type,
    sealType: seal,
    approvalNo: approvalNo,
    createTime: createTime,
  }).then(() => {
    proxy.$modal.msgSuccess("用印信息保存成功");
    fetchFeiShuApprovalTaskMessage();
  });
}

// Data Fetching
async function getCarrierInfoData() {
  const companyId = route.query.companyId || route.params.companyId;
  const params = {
    companyId,
    type: contractType.value,
    processId: route.query.processId || "",
  };
  try {
    const { data } = await getDraftContract(params);
    if (data) {
      Object.assign(contractForm.value, data);
      // Restore form state from fetched data
      if (data.roomNumber) {
        contractForm.value.roomNumber =
          typeof data.roomNumber === "string"
            ? data.roomNumber.split(",")
            : data.roomNumber;
      }
      if (data.paymentTerms) {
        const payMatch = data.paymentTerms.match(/付(\d+)/);
        const depositMatch = data.paymentTerms.match(/押(\d+)/);
        payNum.value = payMatch ? payMatch[1] : "1";
        depositNum.value = depositMatch ? depositMatch[1] : "1";
      }
      if (data.leaseTerm) {
        const cnDateToISO = (str) => {
          const y = str.match(/(\d{4})年/)[1];
          const m = str.match(/年(\d{1,2})月/)[1].padStart(2, "0");
          const d = str.match(/月(\d{1,2})日/)[1].padStart(2, "0");
          return y && m && d ? `${y}-${m}-${d}` : "";
        };
        const dateMatch = data.leaseTerm.match(/自(.*?)起至(.*?)止/);
        if (dateMatch) {
          leaseDateRange.value = [cnDateToISO(dateMatch[1]), cnDateToISO(dateMatch[2])];
        } else {
          const singleDateMatch = data.leaseTerm.match(/自(.*?)起/);
          if (singleDateMatch)
            leaseDateRange_start.value = cnDateToISO(singleDateMatch[1]);
        }
        const yearMatch =
          data.leaseTerm.match(/共计(\d+)年/) || data.leaseTerm.match(/租赁期(\d+)年/);
        leaseYears.value = yearMatch ? yearMatch[1] : "";
        contractForm.value.year = yearMatch ? yearMatch[1] : "";
      }

      // 读取旧合同信息
      if (data.sourceContract) {
        fetchOldContractInfo(data.sourceContract);
      } else {
        oldContractInfo.value = null;
        oldContractPlans.value = [];
      }
      fetchPlanList();
    } else {
      const { data: carrierData } = await getCarrierInfo({ companyId });
      if (carrierData) {
        contractForm.value.carrierInfo = { ...carrierData };
        contractForm.value.address = carrierData.lessorAddress || "";
      }
      oldContractInfo.value = null;
      oldContractPlans.value = [];
    }
  } catch (e) {
    console.error("获取合同草稿或出租方信息失败:", e);
    oldContractInfo.value = null;
    oldContractPlans.value = [];
  }
}

// 拉取旧合同信息和回款计划
async function fetchOldContractInfo(contractNumber) {
  if (!contractNumber) {
    oldContractInfo.value = null;
    oldContractPlans.value = [];
    return;
  }
  try {
    // 获取旧合同基本信息
    const res = await getDraftContract({ contractNumber });
    if (res && res.data) {
      oldContractInfo.value = res.data;
    } else {
      oldContractInfo.value = null;
    }
    // 获取旧合同回款计划
    const planRes = await getPaymentPlanListNew({
      contractNumber,
      pageNum: 1,
      pageSize: 100,
    });
    oldContractPlans.value = planRes && planRes.rows ? planRes.rows : [];
  } catch (e) {
    oldContractInfo.value = null;
    oldContractPlans.value = [];
  }
}

// 获取房间状态文本
function getRoomStatusText(status) {
  const statusMap = {
    0: "未出租",
    1: "占用中",
    2: "已出租",
  };
  return statusMap[status] || "未知";
}

// 判断房间是否属于当前合同
function isRoomBelongsToContract(roomId) {
  if (!contractForm.value.roomId) return false;
  const contractRoomIds = contractForm.value.roomId.split(",").filter((id) => id);
  return contractRoomIds.includes(String(roomId));
}

// 判断房间是否应该禁用
function isRoomDisabled(item) {
  // 如果状态为0（未出租），不禁用
  if (item.status === 0) return false;
  // 如果状态不为0但房间属于当前合同，不禁用
  if (isRoomBelongsToContract(item.id)) return false;
  // 其他情况（状态不为0且不属于当前合同），禁用
  return true;
}

async function fetchFreeRooms() {
  try {
    console.log("contractForm.value.carrierName:", contractForm.value.carrierName);
    const res = await getAllRoomList({
      contractNumber: contractForm.value.contractNumber,
      zt: route.query.carrierName,
    });
    freeRooms.value = res.rows || [];
  } catch (e) {
    freeRooms.value = [];
  }
}

async function fetchFeiShuApprovalTaskMessage() {
  if (!contractForm.value.contractNumber) return;
  try {
    const approvalType = contractType.value === "虚拟" ? "虚拟" : "实体";
    const res = await getFeiShuApprovalTaskMessage({
      contractNumber: contractForm.value.contractNumber,
      approvalType: approvalType,
      companyId: route.query.companyId || route.params.companyId,
    });
    if (res.rows[0]) {
      isContractSealDisabled.value = true;
      const task = res.rows[0];
      if (contractType.value === "虚拟") {
        sealVirtualType.value = task.sealType || "实体章";
        approvalVirtualNumber.value = task.approvalNo || "";
        createTimeVirtual.value = task.createTime || new Date();
      } else {
        sealType.value = task.sealType || "实体章";
        approvalNumber.value = task.approvalNo || "";
        createTimeSeal.value = task.createTime || new Date();
      }
    } else {
      isContractSealDisabled.value = false;
    }
  } catch (e) {
    isContractSealDisabled.value = false;
  }
}

function resetContractForm() {
  const companyId = contractForm.value.companyId;
  const lesseeName = contractForm.value.lesseeName;
  contractForm.value = {
    type: contractType.value,
    companyId: companyId,
    lesseeName: lesseeName,
    contractNumber: "",
    carrierName: "",
    carrierInfo: {},
    lesseeContactPerson: "",
    lesseeContactInfo: "",
    lesseeCreditCode: "",
    lesseeAddress: "",
    lesseeBank: "",
    lesseeAccount: "",
    address: "",
    roomNumber: [],
    roomId: "",
    area: "",
    leaseTerm: "",
    rentFreePeriod: "",
    unitRentPrice: "",
    propertyType: "自有物业",
    paymentTerms: "",
    securityDeposit: "",
    amount: "",
    waterExpense: "",
    electricityExpense: "",
    level: "",
    year: "",
    message: "",
    lessorName: "",
  };
  leaseDateRange.value = [];
  leaseDateRange_start.value = "";
  leaseYears.value = "";
  payNum.value = "1";
  depositNum.value = "1";
}
// 添加完成当前模块的处理函数
async function handleCompletePropertyStep() {
  const companyId = route.query.companyId || route.params.companyId;

  if (!contractForm.value.id) {
    proxy.$modal.msgWarning("请完善合同信息");
    return;
  }
  await DraftContractEnd(contractForm.value.contractNumber);
  // 所有条件满足，提交更新
  await submitAndUpdate({ companyId, status: 7, id: route.query.processId || "" }).then(
    (res) => {
      if (res.code === 200) {
        proxy.$modal.msgSuccess("完成入驻流程");

        // 更新路由参数;
        // router.push({
        //   query: {
        //     ...route.query,
        //     companyStatus: 7,
        //   },
        // });
        router.go(-1);
      } else {
        proxy.$modal.msgError(res.msg || "操作失败，请稍后重试");
      }
    }
  );
}

// Lifecycle
onMounted(() => {
  const companyId = route.query.companyId || route.params.companyId;
  if (!companyId) {
    proxy.$modal.msgWarning("未找到公司ID，请返回重试");
    router.push("/company/companyList");
    return;
  }

  companyClass.value = route.query.companyClass || "";
  carrieType.value = route.query.carrieType || "";
  contractForm.value.companyId = companyId;
  contractForm.value.lesseeName = route.query.companyName || "";

  if (!isRehandleCertificate.value) {
    // 根据 carrieType 设置默认的 contractType
    if (carrieType.value && carrieType.value !== "") {
      contractType.value = carrieType.value;
    } else {
      // 如果没有指定 carrieType，根据 zt 判断
      contractType.value =
        route.query.zt == "联健元和" ||
        route.query.zt == "达博" ||
        route.query.zt == "秦淮项目" ||
        route.query.zt == "江环项目"
          ? "孵化器"
          : "加速器";
    }
  }

  goStep(0); // Start at the first step
  getCarrierInfoData();
  fetchFreeRooms();
  // 初始化获取办证材料文件列表
  let tags = [2, 3, 4, 12]; // 法人签字笔迹、自然人身份证、非自然人营业执照、营业执照PDF
  tags.forEach(async (tag) => {
    const params = {
      pageNum: 1,
      pageSize: 20,
      companyId: route.query.companyId,
      tag,
      processId: route.query.processId,
    };
    try {
      const res = await getFileByCompanyIdAndTag(params);
      const files = (res && res.rows ? res.rows : []).map((f) => ({
        id: f.id,
        name: f.name || "",
        url: f.url,
      }));
      if (tag === 2) fileListSign.value = files;
      else if (tag === 3) fileListId.value = files;
      else if (tag === 4) fileListLicense.value = files;
      else if (tag === 12) fileListLicensePdf.value = files;
    } catch (e) {
      console.error("文件回显失败", e);
    }
  });
});

watch(activeStep, (newStep) => {
  const companyId = route.query.companyId || route.params.companyId;
  if (!companyId) return;

  if (newStep === 0) {
    // 合同
    getCarrierInfoData();
    fetchFreeRooms();
    fetchPlanList();
    fetchFeiShuApprovalTaskMessage();
    refreshFileListByTag(7);
    refreshFileListByTag(14);
  } else if (newStep === 1) {
    // 办证
    [2, 3, 4].forEach((tag) => refreshFileListByTag(tag));
  }
});

watch(
  () => contractForm.value.contractNumber,
  (val) => {
    if (val) {
      fetchPlanList();
      fetchFeiShuApprovalTaskMessage();
    }
  }
);
</script>

<style scoped>
.record-container {
  padding: 24px 32px 0 32px;
  min-height: 100vh;
}
.company-step-container {
  padding: 24px;
  border-radius: 8px;
}
.company-main-row {
  min-height: 700px;
}
.company-main-content {
  min-height: 700px;
}
.company-step-side {
  padding-top: 8px;
  margin-bottom: 20px;
}
.vertical-steps {
  width: 100%;
  cursor: pointer;
}
.material-upload-row {
  display: flex;
  gap: 24px;
  margin-top: 20px;
}
.material-block {
  flex: 1;
  padding: 24px;
  border-radius: 8px;
  border: 1px solid #e5e7ef;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}
.block-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}
.material-inner-row {
  display: flex;
  gap: 24px;
}
.upload-vertical {
  display: flex;
  flex-direction: column;
  gap: 20px;
  flex: 1;
}
.upload-section {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.upload-label {
  font-size: 15px;
  font-weight: 500;
}
.block-img {
  width: 200px;
  text-align: center;
}
.full-img {
  width: 100%;
  border-radius: 4px;
  cursor: pointer;
}
.example-label {
  font-size: 13px;
  color: #888;
  margin-top: 8px;
}
.form-section-title {
  font-size: 16px;
  font-weight: 600;
  margin: 24px 0 16px 0;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
}
.form-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 16px;
}
</style>
